package com.xiaode.plugin.obs;

import com.jfinal.kit.Kv;
import com.obs.services.model.*;

import java.util.HashMap;
import java.util.Map;

public class ObsKit {

    /**
     * 获取前端上传参数
     * businessType 1.chat 2.xiaode
     */
    public static Kv getUpParams(String fileName, Integer businessType) {
        PostSignatureRequest request = new PostSignatureRequest();
        request.setExpires(ObsPlugin.expireSeconds);
        // 设置表单参数
//		Map<String, Object> formParams = new HashMap<String, Object>();
//		// 设置对象MIME类型
//		formParams.put("content-type", "text/plain");
        PostSignatureResponse response = ObsPlugin.obsClient.createPostSignature(request);
        Kv kv = Kv.create().set("policy", response.getPolicy())
                .set("signature", response.getSignature())
                .set("accessKeyId", ObsPlugin.ak)
                .set("key", fileName);
        if (businessType == 1) {
            kv.set("uploadUrl", ObsPlugin.chatUrl);
        } else if (businessType == 2) {
            kv.set("uploadUrl", ObsPlugin.xiaodeUrl);
        }
        return kv;
    }

    /**
     * 前端下载
     * isThumbnail参数仅图片可用
     */
    public static String getDownloadUrl(String fileName, Boolean isThumbnail, Integer businessType) {
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, ObsPlugin.expireSeconds);
        String bucketName = null;
        if (businessType == 1){
            bucketName = ObsPlugin.chatBucketName;
        }else if(businessType == 2){
            bucketName = ObsPlugin.xiaodeBucketName;
        }
        request.setBucketName(bucketName);
        request.setObjectKey(fileName);
        if (isThumbnail) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("x-image-process", "image/resize,m_lfit,h_200,w_200");
            request.setQueryParams(map);
        }
        TemporarySignatureResponse response = ObsPlugin.obsClient.createTemporarySignature(request);
        return response.getSignedUrl();
    }

    //删除文件
    public static void deleteFile(String fileName, Integer businessType) {
        String bucketName = null;
        if (businessType == 1){
            bucketName = ObsPlugin.chatBucketName;
        }else if(businessType == 2){
            bucketName = ObsPlugin.xiaodeBucketName;
        }
        ObsPlugin.obsClient.deleteObject(bucketName, fileName);
    }


}
